using Sheep_Breeding.Domain.production_a;
using Sheep_Breeding.ErrorCode;
using Sheep_Breeding.Infeartructure;
using Sheep_Breeding.Read.Api.Dtos;
using Sheep_Breeding.Read.Api.OperationServices.IServices;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace Sheep_Breeding.Read.Api.OperationServices.Services
{
    /// <summary>
    /// 母羊配种查询服务实现类
    /// </summary>
    public class EweMatingServices : IEweMatingServices
    {
        private readonly ILogger<EweMatingServices> _logger;
        private readonly IBaseRepository<Ewe_mating> _eweMatingRepository;
        private readonly IBaseRepository<Ewe_mating_details> _detailsRepo;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger">日志记录器</param>
        /// <param name="eweMatingRepository">母羊配种仓储</param>
        /// <param name="detailsRepo">母羊配种明细仓储</param>
        public EweMatingServices(
            ILogger<EweMatingServices> logger,
            IBaseRepository<Ewe_mating> eweMatingRepository,
            IBaseRepository<Ewe_mating_details> detailsRepo)
        {
            _logger = logger;
            _eweMatingRepository = eweMatingRepository;
            _detailsRepo = detailsRepo;
        }
        
        /// <summary>
        /// 获取母羊配种列表
        /// </summary>
        /// <param name="queryDto">查询条件</param>
        /// <returns>分页结果</returns>
        public async Task<ApiResult<ApiPaging<List<EweMatingListDto>>>> GetEweMatingListAsync(QueryEweMatingDto queryDto)
        {
            var result = new ApiResult<ApiPaging<List<EweMatingListDto>>>();
            
            try
            {
                _logger.LogInformation("开始查询母羊配种列表");
                
                // 使用Repository模式查询
                var matingQuery = _eweMatingRepository.Getlist().Where(x => !x.IsDeleted);
                
                // 应用查询条件
                if (queryDto.BreedingDateStart.HasValue)
                {
                    matingQuery = matingQuery.Where(x => x.BreedingDate >= queryDto.BreedingDateStart.Value);
                }

                if (queryDto.BreedingDateEnd.HasValue)
                {
                    matingQuery = matingQuery.Where(x => x.BreedingDate <= queryDto.BreedingDateEnd.Value);
                }

                if (!string.IsNullOrEmpty(queryDto.EarNumber))
                {
                    matingQuery = matingQuery.Where(x => x.EarNumber.Contains(queryDto.EarNumber));
                }
                
                // 获取总记录数
                var totalCount = matingQuery.Count();
                
                // 分页查询主表数据
                var matingList = matingQuery
                    .OrderByDescending(x => x.BreedingDate)
                    .Skip((queryDto.PageIndex - 1) * queryDto.PageSize)
                    .Take(queryDto.PageSize)
                    .ToList();
                
                // 获取这些主表数据的所有ID
                var breedingIds = matingList.Select(m => m.BreedingId).ToList();
                
                // 查询关联的明细表数据
                var detailsList = _detailsRepo.Getlist()
                    .Where(d => !d.IsDeleted && breedingIds.Contains(d.BreedingId))
                    .ToList();
                
                // 创建结果列表
                var resultList = new List<EweMatingListDto>();
                
                // 遍历主表数据，结合明细表数据
                foreach (var mating in matingList)
                {
                    // 查找对应的明细记录
                    var detail = detailsList.FirstOrDefault(d => d.BreedingId == mating.BreedingId);
                    
                    // 创建DTO对象
                    var dto = new EweMatingListDto
                    {
                        // 主表字段
                        BreedingId = mating.BreedingId ?? string.Empty,
                        BreedingDate = mating.BreedingDate,
                        LastBreedingDate = mating.LastBreedingDate,
                        EarNumber = mating.EarNumber ?? string.Empty,
                        FemaleBreed = mating.FemaleBreed ?? string.Empty,
                        FirstMaleSheep = mating.FirstMaleSheep,
                        ExtraMaleSheep = mating.ExtraMaleSheep,
                        BreedingMethod = mating.BreedingMethod,
                        FemaleEstrusType = mating.FemaleEstrusType,
                        BreedingHouse = mating.BreedingHouse,
                        Creator = mating.Creator,
                        CreateTime = mating.CreateTime,
                        Modifier = mating.Modifier,
                        ModifyTime = mating.ModifyTime
                    };
                    
                    // 如果存在明细记录，则填充明细字段
                    if (detail != null)
                    {
                        dto.EventType = detail.EventType;
                        dto.EventPen = detail.EventPen;
                        dto.TransferInPen = detail.TransferInPen;
                        dto.TransferInHouse = detail.TransferInHouse;
                        dto.PredictionStatus = detail.PredictionStatus;
                        dto.EventDate = detail.EventDate;
                        dto.Principal = detail.Principal;
                        dto.Auditor = detail.Auditor;
                        dto.AuditTime = detail.AuditTime;
                        dto.DocumentNo = detail.DocumentNo;
                    }
                    
                    resultList.Add(dto);
                }
                
                // 创建分页结果
                var paging = new ApiPaging<List<EweMatingListDto>>
                {
                    PageIndex = queryDto.PageIndex,
                    PageSize = queryDto.PageSize,
                    PageData = resultList,
                    TotalCount = totalCount
                };
                
                result.success("查询成功", paging);
                _logger.LogInformation($"查询母羊配种列表成功，共找到 {totalCount} 条记录");
            }
            catch (Exception ex)
            {
                result.msg = $"查询母羊配种列表失败：{ex.Message}";
                _logger.LogError($"查询母羊配种列表异常：{ex.Message}");
            }
            
            return result;
        }

        /// <summary>
        /// 分页查询母羊配种记录
        /// </summary>
        /// <param name="searchDto">查询条件</param>
        /// <returns>分页结果</returns>
        public async Task<ApiResult<ApiPaging<List<Ewe_mating>>>> GetEweMatingList(SearchEweMatingDto searchDto)
        {
            var result = new ApiResult<ApiPaging<List<Ewe_mating>>>();

            try
            {
                // 构建查询条件
                var query = _eweMatingRepository.Getlist().Where(x => !x.IsDeleted);

                // 应用筛选条件
                if (!string.IsNullOrEmpty(searchDto.EarNumber))
                {
                    query = query.Where(x => x.EarNumber.Contains(searchDto.EarNumber));
                }

                if (searchDto.StartDate.HasValue && searchDto.StartDate.Value > DateTime.MinValue)
                {
                    var start = searchDto.StartDate.Value;
                    query = query.Where(x => x.BreedingDate >= start);
                }
                if (searchDto.EndDate.HasValue && searchDto.EndDate.Value > DateTime.MinValue)
                {
                    var end = searchDto.EndDate.Value;
                    query = query.Where(x => x.BreedingDate <= end);
                }

                // 按配种日期降序排序
                query = query.OrderByDescending(x => x.BreedingDate);

                // 获取总记录数
                var totalCount = query.Count();

                // 分页
                var pagedData = query
                    .Skip((searchDto.PageIndex - 1) * searchDto.PageSize)
                    .Take(searchDto.PageSize)
                    .ToList();

                // 构建分页结果，补充TotalCount字段
                var pagingResult = new ApiPaging<List<Ewe_mating>>
                {
                    PageIndex = searchDto.PageIndex,
                    PageSize = searchDto.PageSize,
                    PageData = pagedData,
                    TotalCount = totalCount // 新增：返回总条数，便于前端分页
                };

                result.success("查询成功", pagingResult);
                _logger.LogInformation($"查询母羊配种记录成功，共找到 {totalCount} 条记录");
            }
            catch (Exception ex)
            {
                result.msg = "查询母羊配种记录时发生异常";
                _logger.LogError($"查询母羊配种记录异常：{ex.Message}");
            }

            return result;
        }
        
        /// <summary>
        /// 根据配种编号获取母羊配种详情
        /// </summary>
        /// <param name="breedingId">配种编号</param>
        /// <returns>母羊配种详情</returns>
        public async Task<ApiResult<Ewe_mating>> GetEweMatingById(string breedingId)
        {
            // 为了避免编译错误，先实现空方法
            var result = new ApiResult<Ewe_mating>();
            result.msg = "方法未实现";
            return result;
        }
        
        /// <summary>
        /// 根据耳号获取母羊配种记录
        /// </summary>
        /// <param name="earNumber">耳号</param>
        /// <returns>母羊配种记录</returns>
        public async Task<ApiResult<Ewe_mating>> GetEweMatingByEarNumber(string earNumber)
        {
            // 为了避免编译错误，先实现空方法
            var result = new ApiResult<Ewe_mating>();
            result.msg = "方法未实现";
            return result;
        }
        
        /// <summary>
        /// 主表+明细表联合分页查询（明细只取最新一条）
        /// </summary>
        public async Task<ApiResult<ApiPaging<List<EweMatingWithDetailDto>>>> GetEweMatingWithDetailList(SearchEweMatingDto searchDto)
        {
            // 为了避免编译错误，先实现空方法
            var result = new ApiResult<ApiPaging<List<EweMatingWithDetailDto>>>();
            result.msg = "方法未实现";
            return result;
        }
    }
} 